from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
from typing import List, Dict, Any
import logging

app = FastAPI(
    title="Product Recommendation API",
    description="基于用户历史购买记录的商品推荐服务",
    version="1.0.0"
)

# 导入推荐助手
from assistant.core import ProductRecommendationAssistant

# 初始化助手
recommendation_assistant = ProductRecommendationAssistant()

class User(BaseModel):
    username: str
    purchase_history: List[Dict[str, Any]]

class Product(BaseModel):
    name: str
    category: str
    sub_category: str
    price: float
    merchant: str

@app.on_event("startup")
async def startup_event():
    """加载初始数据"""
    # 这里可以加载数据库中的真实数据
    # 这里使用捏造的数据进行初始化
    users = [...]  # 用户数据
    products = [...]  # 商品数据
    
    recommendation_assistant.load_data(users, products)
    logging.info("Recommendation service initialized.")

@app.post("/api/recommend/products", response_model=List[Product])
async def get_recommended_products(username: str):
    """获取推荐商品"""
    try:
        recommendations = recommendation_assistant.recommend_products(username)
        return recommendations
    except Exception as e:
        logging.error(f"Recommendation failed: {e}")
        raise HTTPException(status_code=500, detail=f"Recommendation service error: {e}")
